// 拦截器放在controllers包下，称为局部拦截器，局部拦截器只作用于所在目录以及子目录的控制器
package com.qd.controllers.lib;

import net.paoding.rose.web.ControllerInterceptorAdapter;
import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Interceptor;

import java.util.concurrent.ExecutorService;

import org.springframework.beans.factory.annotation.Autowired;

import com.qd.lib.model.OperLog;
import com.qd.lib.model.User;
import com.qd.lib.service.OperLogService;

/**
 * @author taomk
 * @version 1.0
 * @since 2014/9/20 12:35
 */
@Interceptor(oncePerRequest = true)
public class AutoLogInterceptor extends ControllerInterceptorAdapter {

	// 这里的executorService，在applicationContext-executor.xml中并没有id="xxx", 但这没有问题，Spring会给该Bean一个默认的id（类全名）
	@Autowired
	private ExecutorService executorService;

	@Autowired
	private OperLogService operLogService;

	public void afterCompletion(Invocation inv,Throwable ex)throws Exception{

		final OperLog operLog=new OperLog();
		operLog.setResourcePattern(inv.getResourceId());
		operLog.setResourceId(inv.getRequestPath().getUri());
		operLog.setSuccess(ex==null? 1 : 0);
		operLog.setRemarks(ex==null? "" : ex.getMessage());
		operLog.setUserName("TaoMingkai");

		// 封装为一个任务
		Runnable task=new Runnable(){
			public void run(){
				operLogService.save(operLog);
			}
		};

		// 将插入到数据库的操作提交executorService做异步更新
		// 在实际场景中，这种方式要注意webapp shutdown的时候，还未执行的Task的处理问题
		executorService.submit(task);
	}
}